<template>
  <div class="emp-info">
    <!-- 详情查看模式 -->
    <div v-if="!isEdit" class="emp-info-detail">
      <div class="emp-info-header">
        <h3>{{ empData.empName || '员工详情' }}</h3>
        <div class="emp-info-actions">
          <el-button type="primary" @click="handleEdit">编辑</el-button>
          <el-button @click="$emit('close')">关闭</el-button>
        </div>
      </div>
      
      <ClientOnly>
        <div class="form-sections">
          <!-- 基础信息 -->
          <div class="form-section">
            <div class="section-title">基础信息</div>
            <PageForm
              ref="detailFormRef"
              :form-data="empData"
              :list="basicInfoFormList"
              :disabled="true"
            />
          </div>

          <!-- 角色与权限 -->
          <div class="form-section">
            <div class="section-title">角色与权限1</div>
            <PageForm
              ref="detailFormRef2"
              :form-data="empData"
              :list="rolePermissionFormList"
              :disabled="true"
            />
          </div>

          <!-- 个人信息 -->
          <div class="form-section">
            <div class="section-title">个人信息</div>
            <PageForm
              ref="detailFormRef3"
              :form-data="empData"
              :list="personalInfoFormList"
              :disabled="true"
            />
          </div>
        </div>
      </ClientOnly>
    </div>

    <!-- 编辑模式 -->
    <div v-else class="emp-info-edit">
      <div class="emp-info-header">
        <h3>编辑员工信息</h3>
        <div class="emp-info-actions">
          <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
          <el-button @click="handleCancelEdit">取消</el-button>
        </div>
      </div>

      <ClientOnly>
        <div class="form-sections">
          <!-- 基础信息 -->
          <div class="form-section">
            <div class="section-title">基础信息</div>
            <PageForm
              ref="editFormRef"
              :form-data="formData"
              :list="editBasicInfoFormList"
              :rules="formRules"
            />
          </div>

          <!-- 角色与权限 -->
          <div class="form-section">
            <div class="section-title">角色与权限</div>
            <PageForm
              ref="editFormRef2"
              :form-data="formData"
              :list="editRolePermissionFormList"
              :rules="formRules"
            />
          </div>

          <!-- 个人信息 -->
          <div class="form-section">
            <div class="section-title">个人信息1</div>
            <PageForm
              ref="editFormRef3"
              :form-data="formData"
              :list="editPersonalInfoFormList"
              :rules="formRules"
            />
          </div>
        </div>
      </ClientOnly>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import type { Employee, EmployeeForm } from '@/types/employee';
import type { PageFormList } from '@/types/PageForm';
import type { FormRules } from 'element-plus';
import { parseBirthFromIdCard, solarToLunarString } from '@/utils/lunar';

// Props
interface Props {
  empData: Employee;
  visible?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

// Emits
const emit = defineEmits<{
  close: [];
  save: [data: EmployeeForm];
}>();

// 响应式数据
const isEdit = ref(false);
const saving = ref(false);
const detailFormRef = ref();
const editFormRef = ref();

// 表单数据
const formData = ref<EmployeeForm>({
  empId: props.empData.empId,
  empNo: props.empData.empNo || '',
  empName: props.empData.empName || '',
  gender: props.empData.gender || '1',
  isEnabled: props.empData.isEnabled || '1',
  phone: props.empData.phone || '',
  deptId: props.empData.deptId || 0,
  title: props.empData.title || '',
  isAdmin: props.empData.isAdmin || '0',
  roleIds: props.empData.roleList?.map(role => role.roleId) || [],
  idCard: props.empData.idCard || '',
  solarBirthday: props.empData.solarBirthday || '',
  lunarBirthday: props.empData.lunarBirthday || '',
  hireDate: props.empData.hireDate || '',
  nativeProvince: props.empData.nativeProvince || '',
  nativeCity: props.empData.nativeCity || '',
  nativeCounty: props.empData.nativeCounty || '',
  homeProvince: props.empData.homeProvince || '',
  homeCity: props.empData.homeCity || '',
  homeCounty: props.empData.homeCounty || '',
  homeAddress: props.empData.homeAddress || '',
  cardNo: props.empData.cardNo || '',
  email: props.empData.email || ''
});

// 当身份证号变化时，自动解析出生日期，填充阳历/阴历生日
watch(
  () => formData.value.idCard,
  (id) => {
  //console.log(id);
  
    const s = (id || '').trim();
    // 为空时清空
    if (!s) {
      formData.value.solarBirthday = '';
      formData.value.lunarBirthday = '';
      return;
    }

    // 仅在长度达到 15 或 18 位时再解析，避免输入中途误清空
    if (s.length === 15 || s.length === 18) {
      const solar = parseBirthFromIdCard(s);
      if (solar) {
        formData.value.solarBirthday = solar;
        formData.value.lunarBirthday = solarToLunarString(solar);
      }
      // 如果长度达标但解析失败，不强制清空，保留用户可能手动选择的生日
    }
  },
  { immediate: true,deep: true }
);

// 基础信息表单配置
const basicInfoFormList: PageFormList = [
  {
    list: [
         {
        span: 24,
        label: '员工头像',
        prop: 'logo',
        component: 'avatarUpload',
      },
      {
        span: 12,
        label: '员工姓名',
        prop: 'empName',
        component: 'input',
        componentProps: {
          placeholder: '请输入员工姓名'
        }
      },
      {
        span: 12,
        label: '工号',
        prop: 'empNo',
        component: 'input',
        componentProps: {
          placeholder: '员工工号'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '性别',
        prop: 'gender',
        component: 'select',
        selectGroupOptions: [
          { label: '男', value: '1' },
          { label: '女', value: '0' }
        ]
      },
      {
        span: 12,
        label: '手机号',
        prop: 'phone',
        component: 'input',
        componentProps: {
          placeholder: '请输入手机号'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '身份证号',
        prop: 'idCard',
        component: 'input',
        componentProps: {
          placeholder: '请输入身份证号'
        }
      },
      {
        span: 12,
        label: '电子邮箱',
        prop: 'email',
        component: 'input',
        componentProps: {
          placeholder: '请输入电子邮箱'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '入职日期',
        prop: 'hireDate',
        component: 'date',
        componentProps: {
          placeholder: '请选择入职日期'
        }
      },
      {
        span: 12,
        label: '在职状态',
        prop: 'isEnabled',
        component: 'select',
        selectGroupOptions: [
          { label: '在职', value: '1' },
          { label: '离职', value: '0' }
        ]
      }
    ]
  }
];

// 角色与权限表单配置
const rolePermissionFormList: PageFormList = [
  {
    list: [
      {
        span: 12,
        label: '所属科室',
        prop: 'deptName',
        component: 'input',
        componentProps: {
          placeholder: '所属科室'
        }
      },
      {
        span: 12,
        label: '职称',
        prop: 'title',
        component: 'input',
        componentProps: {
          placeholder: '职称'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '是否管理员',
        prop: 'isAdmin',
        component: 'select',
        selectGroupOptions: [
          { label: '是', value: '1' },
          { label: '否', value: '0' }
        ]
      },
      {
        span: 12,
        label: '授权角色',
        prop: 'roleList',
        component: 'input',
        componentProps: {
          placeholder: '授权角色'
        }
      }
    ]
  }
];

// 个人信息表单配置
const personalInfoFormList: PageFormList = [
  {
    list: [
      {
        span: 12,
        label: '阳历生日',
        prop: 'solarBirthday',
        component: 'date',
        componentProps: {
          placeholder: '请选择阳历生日'
        }
      },
      {
        span: 12,
        label: '阴历生日',
        prop: 'lunarBirthday',
        component: 'date',
        componentProps: {
          placeholder: '请选择阴历生日'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '籍贯',
        prop: 'nativeProvince',
        component: 'input',
        componentProps: {
          placeholder: '籍贯省市县'
        }
      },
      {
        span: 12,
        label: '工资卡号',
        prop: 'cardNo',
        component: 'input',
        componentProps: {
          placeholder: '请输入工资卡号'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 24,
        label: '详细地址',
        prop: 'homeAddress',
        component: 'textarea',
        componentProps: {
          rows: 3,
          placeholder: '请输入详细地址'
        }
      }
    ]
  }
];

// 编辑模式 - 基础信息表单配置
const editBasicInfoFormList: PageFormList = [
  {
    list: [
      {
        span: 24,
        label: '头像',
        prop: 'logo',
        component: 'avatarUpload',
      },
      {
        span: 12,
        label: '员工姓名',
        prop: 'empName',
        component: 'input',
        componentProps: {
          placeholder: '请输入员工姓名'
        }
      },
      {
        span: 12,
        label: '工号',
        prop: 'empNo',
        component: 'input',
        componentProps: {
          placeholder: '请输入工号'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '性别',
        prop: 'gender',
        component: 'select',
        selectGroupOptions: [
          { label: '男', value: '1' },
          { label: '女', value: '0' }
        ]
      },
      {
        span: 12,
        label: '手机号',
        prop: 'phone',
        component: 'input',
        componentProps: {
          placeholder: '请输入手机号'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '身份证号',
        prop: 'idCard',
        component: 'input',
        componentProps: {
          placeholder: '请输入身份证号'
        }
      },
      {
        span: 12,
        label: '电子邮箱',
        prop: 'email',
        component: 'input',
        componentProps: {
          placeholder: '请输入电子邮箱'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '入职日期',
        prop: 'hireDate',
        component: 'date',
        componentProps: {
          placeholder: '请选择入职日期'
        }
      },
      {
        span: 12,
        label: '在职状态',
        prop: 'isEnabled',
        component: 'select',
        selectGroupOptions: [
          { label: '在职', value: '1' },
          { label: '离职', value: '0' }
        ]
      }
    ]
  }
];

// 编辑模式 - 角色与权限表单配置
const editRolePermissionFormList: PageFormList = [
  {
    list: [
      {
        span: 12,
        label: '所属科室',
        prop: 'deptId',
        component: 'select',
        selectGroupOptions: [
          { label: '内科', value: 1 },
          { label: '外科', value: 2 },
          { label: '儿科', value: 3 },
          { label: '妇科', value: 4 }
        ]
      },
      {
        span: 12,
        label: '职称',
        prop: 'title',
        component: 'input',
        componentProps: {
          placeholder: '请输入职称'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '是否管理员',
        prop: 'isAdmin',
        component: 'select',
        selectGroupOptions: [
          { label: '是', value: '1' },
          { label: '否', value: '0' }
        ]
      },
      {
        span: 12,
        label: '',
        prop: '',
        component: 'slot',
        slotName: 'empty'
      }
    ]
  }
];

// 编辑模式 - 个人信息表单配置
const editPersonalInfoFormList: PageFormList = [
  {
    list: [
      {
        span: 12,
        label: '阳历生日',
        prop: 'solarBirthday',
        component: 'date',
        componentProps: {
          placeholder: '请选择阳历生日'
        }
      },
      {
        span: 12,
        label: '阴历生日',
        prop: 'lunarBirthday',
        component: 'date',
        componentProps: {
          placeholder: '请选择阴历生日'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 12,
        label: '籍贯省',
        prop: 'nativeProvince',
        component: 'input',
        componentProps: {
          placeholder: '请输入籍贯省'
        }
      },
      {
        span: 12,
        label: '工资卡号',
        prop: 'cardNo',
        component: 'input',
        componentProps: {
          placeholder: '请输入工资卡号'
        }
      }
    ]
  },
  {
    list: [
      {
        span: 24,
        label: '详细地址',
        prop: 'homeAddress',
        component: 'textarea',
        componentProps: {
          rows: 2,
          placeholder: '请输入详细地址'
        }
      }
    ]
  }
];

// 表单验证规则
const formRules: FormRules = {
  empName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '员工姓名长度为2-20个字符', trigger: 'blur' }
  ],
  empNo: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { min: 3, max: 20, message: '工号长度为3-20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  deptId: [
    { required: true, message: '请选择所属科室', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入职称', trigger: 'blur' }
  ],
  isEnabled: [
    { required: true, message: '请选择在职状态', trigger: 'change' }
  ],
  isAdmin: [
    { required: true, message: '请选择是否管理员', trigger: 'change' }
  ],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

// 监听props变化，更新表单数据
watch(
  () => props.empData,
  (newData) => {
    if (newData) {
      formData.value = {
        empId: newData.empId,
        empNo: newData.empNo || '',
        empName: newData.empName || '',
        gender: newData.gender || '1',
        isEnabled: newData.isEnabled || '1',
        phone: newData.phone || '',
        deptId: newData.deptId || 0,
        title: newData.title || '',
        isAdmin: newData.isAdmin || '0',
        roleIds: newData.roleList?.map(role => role.roleId) || [],
        idCard: newData.idCard || '',
        solarBirthday: newData.solarBirthday || '',
        lunarBirthday: newData.lunarBirthday || '',
        hireDate: newData.hireDate || '',
        nativeProvince: newData.nativeProvince || '',
        nativeCity: newData.nativeCity || '',
        nativeCounty: newData.nativeCounty || '',
        homeProvince: newData.homeProvince || '',
        homeCity: newData.homeCity || '',
        homeCounty: newData.homeCounty || '',
        homeAddress: newData.homeAddress || '',
        cardNo: newData.cardNo || '',
        email: newData.email || ''
      };
    }
  },
  { deep: true, immediate: true }
);

// 编辑操作
const handleEdit = () => {
  isEdit.value = true;
};

// 取消编辑
const handleCancelEdit = () => {
  isEdit.value = false;
  // 重置表单数据
  formData.value = {
    empId: props.empData.empId,
    empNo: props.empData.empNo || '',
    empName: props.empData.empName || '',
    gender: props.empData.gender || '1',
    isEnabled: props.empData.isEnabled || '1',
    phone: props.empData.phone || '',
    deptId: props.empData.deptId || 0,
    title: props.empData.title || '',
    isAdmin: props.empData.isAdmin || '0',
    roleIds: props.empData.roleList?.map(role => role.roleId) || [],
    idCard: props.empData.idCard || '',
    solarBirthday: props.empData.solarBirthday || '',
    lunarBirthday: props.empData.lunarBirthday || '',
    hireDate: props.empData.hireDate || '',
    nativeProvince: props.empData.nativeProvince || '',
    nativeCity: props.empData.nativeCity || '',
    nativeCounty: props.empData.nativeCounty || '',
    homeProvince: props.empData.homeProvince || '',
    homeCity: props.empData.homeCity || '',
    homeCounty: props.empData.homeCounty || '',
    homeAddress: props.empData.homeAddress || '',
    cardNo: props.empData.cardNo || '',
    email: props.empData.email || ''
  };
};

// 保存操作
const handleSave = async () => {
  if (!editFormRef.value) return;
  
  try {
    // 表单验证 - 验证所有分组表单
    await editFormRef.value.validate();
    
    saving.value = true;
    
    // 这里可以调用API保存数据
    // await updateEmployee(formData.value);
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    ElMessage.success('保存成功');
    isEdit.value = false;
    emit('save', formData.value);
    
  } catch (error) {
    //console.error('保存失败:', error);
    //ElMessage.error('保存失败，请检查表单信息');
  } finally {
    saving.value = false;
  }
};
</script>

<style lang="scss" scoped>
.emp-info {
  height: 100%;
  display: flex;
  flex-direction: column;

  .emp-info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0 20px 0;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .emp-info-actions {
      display: flex;
      gap: 10px;
    }
  }

  .emp-info-detail,
  .emp-info-edit {
    flex: 1;
    overflow-y: auto;
  }

  .form-sections {
    .form-section {
      margin-bottom: 30px;

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 2px solid #409eff;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          bottom: -2px;
          width: 30px;
          height: 2px;
          background: #409eff;
        }
      }
    }
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;

    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }

    .el-input,
    .el-select,
    .el-input-number {
      width: 100%;
    }

    .el-textarea {
      .el-textarea__inner {
        resize: vertical;
      }
    }
  }
}
</style>
